<?php
if (!empty($setmodules))
{
	$module['GENERAL']['BLOG'] = basename(__FILE__) .'?mode=list';
	return;
}

require('./pagestart.php');
require(INC_DIR . 'functions_admin_blog.php');
require(INC_DIR . 'bbcode.php');

$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$blogs_id = isset($_GET['id']) ? (int) $_GET['id'] : '';
$submit  = isset($_POST['submit']);
$blog_select = isset($_POST['select']) ? implode(',', $_POST['select']) : '';
$blog_action = isset($_POST['blog_action']) ? $_POST['blog_action'] : '';

switch ($mode)
{
	 case 'list':
		$sql = DB()->fetch_rowset("SELECT * FROM ". TS_BLOGS ." ORDER BY blog_id");
		
		foreach ($sql as $i => $row)
		{
			$template->assign_block_vars('list', array(
				'BLOG_ID'      => $i + 1,
				'BLOGS_ID'     => $row['blog_id'],
				'BLOG_TITLE'   => wbr(str_short($row['blog_title'], 50)),
				'BLOG_TEXT'	   => wbr(str_short($row['blog_text'], 200)),
				'BLOG_POSTER'  => $row['blog_poster'],
				'BLOG_TIME'	   => $row['blog_time'],
			));
		}

		$template->assign_vars(array(
			'TPL_BLOG_LIST' => true,
			'S_BLOG_ACTION' => 'admin_blog.php',
			'S_MODE'        => 'list',
		));
		break;
		
		case 'edit':
			$sql = DB()->fetch_rowset("SELECT * FROM ". TS_BLOGS ." WHERE blog_id = $blogs_id");	
			
			foreach ($sql as $row)
			{
				$template->assign_vars(array(
					'BLOGS_ID'     		=> $row['blog_id'],
					'SHOW_INDEX_BLOG'	=> $row['show_blog_of_index'],
					'ENABLED_COMMENT'	=> $row['enabled_comment'],
					'BLOG_TITLE'   		=> $row['blog_title'],
					'BLOG_TEXT'	   		=> $row['blog_text'],
					'BLOG_POSTER'  		=> $row['blog_poster'],
					'BLOG_TIME'	   		=> $row['blog_time'],
				));
			}
			
			$template->assign_vars(array(
				'TPL_BLOG_EDIT'     => true,
				'S_BLOG_ACTION'     => 'admin_blog.php',
				'S_MODE'            => 'edit',
			));
			break;
			
		case 'add':
			$template->assign_vars(array(
				'TPL_BLOG_EDIT'     => true,
				'S_BLOG_ACTION'     => 'admin_blog.php',
				'S_MODE'            => 'add',
				'BLOGS_ID'          => 'none',
				'SHOW_INDEX_BLOG'	=> 0,
				'ENABLED_COMMENT'	=> 0,
				'BLOG_TITLE'        => '',
				'BLOG_POSTER'       => '',
				'BLOG_TEXT'         => '',
			));
			break;
			
		case 'delete':
			delete_blogs($blogs_id);
			ts_die("Новость удалена!");
		break;
}

if ($submit)
{
	if ($_POST['mode'] == 'list')
	{
		if($blog_action == 'delete' && $blog_select)
		{
			delete_blogs($blog_select);
		}
		redirect('admin/'.basename(__FILE__) . '?mode=list');
	}
	else if(validate_blog_post($_POST) == 1)
	{
		if ($_POST['mode'] == 'edit')
		{
			update_blogs($_POST);
		}
		else if ($_POST['mode'] == 'add')
		{
			insert_blogs($_POST);
		}
		else ts_die('Mode error');
		
		redirect('admin/'.basename(__FILE__) . '?mode=list');
	}
	else
	{
		ts_die(validate_blog_post($_POST));
	}
}

print_page('admin_blog.tmpl', 'admin');